package cn.afactory.tygz.ui.user;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.harwkin.nb.camera.BaseImgView;
import com.harwkin.nb.camera.CropBuilder;
import com.harwkin.nb.camera.callback.CameraImageListener;
import com.harwkin.nb.camera.options.CameraOptions;
import com.harwkin.nb.camera.pop.CameraPop;
import com.harwkin.nb.camera.pop.CameraPopListener;
import com.harwkin.nb.camera.type.OpenType;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;

import cn.afactory.tygz.R;
import cn.afactory.tygz.common.Gendar;
import cn.afactory.tygz.model.Address;
import cn.afactory.tygz.model.SnsSubjectDetailList;
import cn.afactory.tygz.model.UploadFileInfoList;
import cn.afactory.tygz.model.UserInfo;
import cn.afactory.tygz.net.NetManager;
import cn.afactory.tygz.net.lsn.OnResponseListener;
import cn.afactory.tygz.ui.base.BaseActivity;
import cn.afactory.tygz.ui.base.utils.LocalUtils;
import cn.afactory.tygz.ui.base.utils.NaviUtils;
import cn.afactory.tygz.ui.base.utils.SPUtils;
import cn.afactory.tygz.ui.base.utils.StringUtils;
import cn.afactory.tygz.ui.common.HomeTownSelectActivity;

/**
 * Created with Android Studio.
 * Title:UserInfoCollectionActivity
 * Description:
 * Copyright:Copyright (c) 2014
 * Company:中国平安健康保险有限公司
 * Author:Alice
 * Date:15/9/10
 * Time:上午10:05
 * Version 1.0
 */
public class UserInfoCollectionActivity extends BaseActivity implements CameraPopListener,
        CameraImageListener {
    private static final String TAG = UserInfoCollectionActivity.class.getSimpleName();
    private static String[] ALL_RANDOM_NAMES = new String[]{
            "坑巅的小模样", "丢弃微萌的记忆", "残旈逝暗香", "当心情被撕碎", "捂着心说胃疼", "酒酒不能忘怀",
            "醉酒写忧愁", "孤独的流浪客", "落泪让人温柔", "急眼的家巧", "记忆丶定格`", "微凉の青春", "ゞ潮流。单身", "ら不分手的誓言",
            "ゞ苦涩、无法释怀", "今生缤纷了回忆つ", "休闲★永恒", "无奈的蝴蝶", "你说的永久、不后悔", "埋葬…伤痛",
            "向阳花、幽雅", "回忆、谁黯伤", "浅唱、若相爱", "何时再相见し", "咱有的是逗", "无声的语言",
            "夜～那么落寞", "纠结_已成歌", "轮回之后的窒息", "残留着泪珠的眼睛", "无人的角落", "沉落的黄昏",
            "时光让我爱着她", "无情の伤悲", "凝醉～心累", "紫色的回忆", "孤独的晚风", "烟熏妆╮很淡", "笑迎这结局",
            "嗜血 シ成魔", "暗香飘情愁", "花落、若别离", "盛开de、旧蔷薇", "纠结、落泪", "沉默是我最后温柔",
            "加菲猫","流氓兔","柯南","蜡笔小新","樱木花道","卡卡西","蓝精灵",
            "小熊维尼","樱桃小丸子","米老鼠","唐老鸭","龙猫","麦兜","机器猫",
            "一休哥","阿童木","皮卡丘","悟空","阿拉蕾","史努比","皮诺曹",
            "兔八哥","白雪公主","小樱","蜘蛛侠","蝙蝠侠","超人","史瑞克",
            "HelloKitty","大力水手","咸蛋超人","星矢","紫龙","冰河",
            "忍者神龟","芭比","高达","大脸猫","大头儿子","小头爸爸","海尔兄弟",
            "孙悟空","斑点狗","黑猫警长","葫芦娃","喜羊羊","灰太狼"
    };
    public static final int REQ_ADD_ADDRESS_CODE = 101;
    //家乡
    public static final int REQ_ADD_HOMETOWN_ADDRESS_CODE = 102;
    //所在地
    public static final int REQ_ADD_LOCATION_ADDRESS_CODE = 103;
    private TextView tv_hometown_select;
    private EditText et_nick_name;
    private TextView btn_get_random;
    private ImageView iv_gendar_male;
    private ImageView iv_gendar_female;
    private ImageView iv_gendar_other;
    private TextView btn_register;
    private RelativeLayout rl_image_selected;
    private ImageView iv_head_icon;

    private Address mAddressBean;
    private String mHeadIconPath = null;
    private CameraPop mCameraPop;
    private int gendar = Gendar.MALE;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ac_user_info_collect);
        setTitleText("注册");
        initUI();

        initCamera();
    }

    //初始化UI
    private void initUI(){
        tv_hometown_select = (TextView)findViewById(R.id.tv_hometown_select);
        tv_hometown_select.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                gotoSelectCity();
            }
        });

        et_nick_name = (EditText)findViewById(R.id.et_nick_name);
        btn_get_random = (TextView)findViewById(R.id.btn_get_random);
        iv_gendar_male = (ImageView)findViewById(R.id.iv_gendar_male);
        iv_gendar_female = (ImageView)findViewById(R.id.iv_gendar_female);
        iv_gendar_other = (ImageView)findViewById(R.id.iv_gendar_other);
        btn_register = (TextView)findViewById(R.id.btn_register);
        rl_image_selected = (RelativeLayout)findViewById(R.id.rl_image_selected);
        iv_head_icon = (ImageView)findViewById(R.id.iv_head_icon);

        rl_image_selected.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doPickHeadIcon();
            }
        });

        btn_get_random.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doGetRandomNickName();
            }
        });

        iv_gendar_male.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doSwitchGendar(R.id.iv_gendar_male);
            }
        });

        iv_gendar_other.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doSwitchGendar(R.id.iv_gendar_other);
            }
        });

        iv_gendar_female.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doSwitchGendar(R.id.iv_gendar_female);
            }
        });

        btn_register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doUpdateUserInfo();
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (REQ_ADD_ADDRESS_CODE == requestCode) {
            showAddress(resultCode, data);
        }else {
            if (mCameraPop != null) {
                mCameraPop.forResult(requestCode, resultCode, data);
            }
        }
    }

    /**
     * 选择头像
     */
    private void doPickHeadIcon(){
        mCameraPop.showMenu(iv_head_icon);
    }
    /**
     * 获取随机的昵称
     */
    private void doGetRandomNickName(){
        int index = (int)(Math.random()*ALL_RANDOM_NAMES.length);
        if(index - 1 > (ALL_RANDOM_NAMES.length - 1)){
            index = ALL_RANDOM_NAMES.length;
        }

        if(index - 1 < 0){
            index = 1;
        }
        String nickName =  ALL_RANDOM_NAMES[index - 1];
        et_nick_name.setText(nickName);
    }

    private void initCamera() {
        if (mCameraPop == null) {
            mCameraPop = new CameraPop(this, this,this);
        }
    }

    /**
     * 性别切换
     * @param id
     */
    private void doSwitchGendar(int id){
        clearSelectedStatus();
        switch (id){
            case R.id.iv_gendar_male:
                iv_gendar_male.setImageResource(R.drawable.gender_male_checked);
                gendar = Gendar.MALE;
                break;
            case R.id.iv_gendar_female:
                iv_gendar_female.setImageResource(R.drawable.gender_female_checked);
                gendar = Gendar.FEMALE;
                break;
            case R.id.iv_gendar_other:
                iv_gendar_other.setImageResource(R.drawable.gender_other_checked);
                gendar = Gendar.OTHER;
                break;
        }

    }

    private void clearSelectedStatus(){
        iv_gendar_male.setImageResource(R.drawable.gender_male);
        iv_gendar_female.setImageResource(R.drawable.gender_female);
        iv_gendar_other.setImageResource(R.drawable.gender_other);
    }

    /**
     * 选择省份
     */
    private void gotoSelectCity() {
        HomeTownSelectActivity.gotoSelectHometown(this,mAddressBean,REQ_ADD_ADDRESS_CODE);
    }

    /**
     * 展示城市
     * @param resultCode
     * @param data
     */
    private void showAddress(int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            Address addressCodeName = (Address) data
                    .getSerializableExtra(SPUtils.EXTRA_DATA);
            if (null == mAddressBean) {
                mAddressBean = new Address();
            }
            mAddressBean.city = addressCodeName.city;
            mAddressBean.cityCode = addressCodeName.cityCode;
            mAddressBean.areaCode = addressCodeName.areaCode;
            mAddressBean.area = addressCodeName.area;
            mAddressBean.province = addressCodeName.province;
            mAddressBean.provinceCode = addressCodeName.provinceCode;
            StringBuffer buffer = new StringBuffer();
            showCity(addressCodeName, buffer);
            tv_hometown_select.setText(buffer.toString());
        }
    }

    private void showCity(Address addressCodeName, StringBuffer buffer) {
        buffer.append(StringUtils.nullToEmpty(addressCodeName.province));
        buffer.append("  ");
        buffer.append(StringUtils.nullToEmpty(addressCodeName.city));
        if(!StringUtils.isEmpty(addressCodeName.city)){
            buffer.append("  ");
        }
        if(!StringUtils.isEmpty(addressCodeName.area)){
            buffer.append(StringUtils.nullToEmpty(addressCodeName.area));
        }
    }

    /**
     * 更新个人信息
     */
    private void doUpdateUserInfo(){
        if(StringUtils.isEmpty(mHeadIconPath)){
            LocalUtils.showToast(this,"请选择一个头像");
            return ;
        }
        String nickName = et_nick_name.getText().toString().trim();
        if(StringUtils.isEmpty(nickName)){
            LocalUtils.showToast(this,"请选择一个昵称");
            return ;
        }
        String city = tv_hometown_select.getText().toString().trim();
        if(getString(R.string.label_hint_hometown_select).equals(city)){
            LocalUtils.showToast(this,"请选择你的家乡");
            return ;
        }
        showLoadingView("更新个人资料中...");
        NetManager.getInstance(this).doUpdateUserInfo(mHeadIconPath,
                nickName,
                gendar,
                mAddressBean.cityCode,
                mAddressBean.city,
                -1,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                new OnResponseListener<UserInfo>() {
            @Override
            public void onComplete(boolean isOK, UserInfo result, int errorCode, String errorMsg) {
                hideLoadingView();
                if(isOK && result != null){
                    LocalUtils.showToast(UserInfoCollectionActivity.this,"开启新旅程!");
                    gotoMain();
                }else{
                    LocalUtils.showToast(UserInfoCollectionActivity.this,errorMsg);
                }
            }

            @Override
            public void onInternError(int errorCode, String errorMessage) {
                hideLoadingView();
                LocalUtils.showToast(UserInfoCollectionActivity.this,errorMessage);
            }
        });
    }

    private void gotoMain(){
        NaviUtils.gotoMain(this);
        finish();
    }

    @Override
    public void onCamreaClick(CameraOptions options) {
        options.setOpenType(OpenType.OPEN_CAMERA_CROP)
                .setCropBuilder(new CropBuilder(1, 1, 300, 300));
        managerProcess();
    }

    @Override
    public void onPickClick(CameraOptions options) {
        options.setOpenType(OpenType.OPEN_GALLERY_CROP)
                .setCropBuilder(new CropBuilder(1, 1, 300, 300));
        managerProcess();
    }

    @Override
    public void onDelClick() {

    }

    /**
     * 执行照片处理
     */
    private void managerProcess() {
        mCameraPop.process();
        if (null != mCameraPop) {
            mCameraPop.dismiss();
        }
    }

    @Override
    public void onSelectedAsy(String imgPath) {
        UpImagefromCut(imgPath);
    }

    protected void UpImagefromCut(String data) {
        if (data == null) {
            return;
        }
        if (data != null && data.length() > 0) {
            UploadImage(data);
        }
    }

    protected void UploadImage(final String file) {
        showLoadingView("头像上传中...");
        NetManager.getInstance(this).doUploadImage(file,
                "1",
                new OnResponseListener<UploadFileInfoList>() {

                    @Override
                    public void onInternError(int errorCode, String errorMessage) {
                        hideLoadingView();
                        LocalUtils.showToast(UserInfoCollectionActivity.this, errorMessage);
                    }

                    @Override
                    public void onComplete(boolean isOK, UploadFileInfoList result, int errorCode, String errorMsg) {
                        hideLoadingView();
                        if (isOK) {
                            if (result != null&& result.data.size() > 0) {
                                mHeadIconPath = String.valueOf(result.data.get(0).fileId);
                                String url = result.data.get(0).url;
                                BaseImgView.loadimg(iv_head_icon, url,
                                        R.drawable.ic_pic_loading_default_small,
                                        R.drawable.ic_pic_loading_default_small,
                                        R.drawable.ic_pic_loading_default_small,
                                        ImageScaleType.EXACTLY,
                                        (int) mContext.getResources().getDimension(R.dimen.healthcircle_padding30),
                                        (int) mContext.getResources().getDimension(R.dimen.healthcircle_padding30),
                                        0);
                            } else {
                                LocalUtils.showToast(UserInfoCollectionActivity.this, "头像上传失败，请稍候重试");
                            }
                        } else {
                            LocalUtils.showToast(UserInfoCollectionActivity.this,errorMsg);
                        }
                    }
                });
    }
}
